﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Collections.ObjectModel;
using System.ServiceModel;
using GUI.ServiceAgents;
using System.Diagnostics;
using GUI.AirportSVC;

namespace GUI.ViewModels
{
    public class MainPageViewModel : ViewModelBase
    {
        private ObservableCollection<Flight> _FlightList = new ObservableCollection<Flight>();

        public ObservableCollection<Flight> FlightList
        {
            get { return _FlightList; }

            set
            {
                if (_FlightList != value)
                {
                    _FlightList = value;
                    OnPropertyChanged("FlightList");
                }
            }
        }

        public MainPageViewModel()
            : this(new AirportServiceAgent())
        {
        }

        public MainPageViewModel(IAirportServiceAgent airportServiceAgent)
        {
            if (!IsDesignTime)
            {
                //_FlightList = new ObservableCollection<string>();

                if (airportServiceAgent != null) 
                    AServiceAgent = airportServiceAgent;
                ConnectToAirportService();
            }
        }

        private IAirportServiceAgent AServiceAgent { get; set; }

        private void ConnectToAirportService()
        {
            //AServiceAgent.ConnectToAirportService((s, e) => FlightList.Add(e.Result));
            AServiceAgent.ConnectToAirportService((s, e) => c_newFlightUpdateReceived(s, e));
        }

        private void c_newFlightUpdateReceived(object sender, AirportSVC.newFlightUpdateReceivedEventArgs e)
        {
            try
            {
                if (e.Error == null)
                {
                    //_updates.Add(e.str);
                    _FlightList.Add(e.newFlight);
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine("MainPageViewModel: {0}", ex.Message);
                Debug.WriteLine("                   {0}", ex.StackTrace);
                Debug.WriteLine("                   {0}", ex.InnerException.Message);
            }
        }

        
    }
}
